from django.db import models
from django.db.models.signals import pre_delete 
from django.dispatch.dispatcher import receiver
import os
# Create your models here.

class Photo(models.Model):
    title = models.CharField(default='', max_length=64)
    location = models.CharField(max_length=255)

    def __str__(self):
        return str(self.title)
    class Meta:
        managed=True
        verbose_name = '图片'
        verbose_name_plural = verbose_name

@receiver(pre_delete, sender=Photo)
def delete_photo(instance, **kwargs):      
    fpath = instance.location
    print("删除:"+fpath)
    try:
        print("尝试删除原文件...")
        os.remove(fpath)
    except:
        pass
    print("文件已被删除")
    try:
        print("尝试删除相关文件...")
        os.remove(fpath.replace("static/upload/","static/generated"))
    except:
        pass
    print("文件已被删除")
